package com.lh.service.impl;

import com.lh.enums.OrderStatusEnum;
import com.lh.enums.YesOrNo;
import com.lh.mapper.OrderItemsMapper;
import com.lh.mapper.OrderStatusMapper;
import com.lh.mapper.OrdersMapper;
import com.lh.pojo.Items;
import com.lh.pojo.ItemsImg;
import com.lh.pojo.ItemsSpec;
import com.lh.pojo.OrderItems;
import com.lh.pojo.OrderStatus;
import com.lh.pojo.Orders;
import com.lh.pojo.UserAddress;
import com.lh.pojo.bo.CreateOrderBO;
import com.lh.pojo.vo.MerchantOrdersVO;
import com.lh.pojo.vo.OrderVO;
import com.lh.service.ItemService;
import com.lh.service.OrderService;
import com.lh.service.UserAddressService;
import com.lh.utils.DateUtil;
import org.aspectj.weaver.ast.Or;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @program: foodie-dev
 * @description:
 * @author: LH
 * @create: 2022-05-20 16:43
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private Sid sid;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public OrderVO create(CreateOrderBO createOrderBO) {

        String userId = createOrderBO.getUserId();
        String itemSpecIds = createOrderBO.getItemSpecIds();
        String addressId = createOrderBO.getAddressId();
        Integer payMethod = createOrderBO.getPayMethod();
        String leftMsg = createOrderBO.getLeftMsg();
        //邮费设置为0
        Integer postAmount = 0;

        //1.插入订单表
        Orders newOrder = new Orders();

        //生成订单id
        String orderId = sid.nextShort();
        newOrder.setId(orderId);
        newOrder.setUserId(userId);

        //组装收货地址信息
        UserAddress userAddress = userAddressService.getUserAddressById(addressId);
        newOrder.setReceiverName(userAddress.getReceiver());
        newOrder.setReceiverMobile(userAddress.getMobile());
        newOrder.setReceiverAddress(userAddress.getProvince()
                + " " + userAddress.getCity()
                + " " + userAddress.getDistrict()
                + " " + userAddress.getDetail());

        //组装实际金额和订单总金额
        String[] itemSpecIdArray = itemSpecIds.split(",");
        Integer totalAmount = 0;    //订单总价格
        Integer realPayAmount = 0;  //实际支付总价格
        for (int i = 0; i < itemSpecIdArray.length; i++) {

            // TODO 整合redis后，商品购买的数量重新从redis的购物车中获取
            Integer buyCounts = 1;

            ItemsSpec itemsSpec = itemService.getItemsSpecById(itemSpecIdArray[i]);
            totalAmount += buyCounts * itemsSpec.getPriceNormal();
            realPayAmount += buyCounts * itemsSpec.getPriceDiscount();

            //2.循环保存订单商品表
            OrderItems newOrderItems = new OrderItems();
            String orderItemsId = sid.nextShort();
            newOrderItems.setId(orderItemsId);
            newOrderItems.setOrderId(orderId);
            newOrderItems.setItemId(itemsSpec.getItemId());
            ItemsImg itemsImg = itemService.queryItemImgByItemIdAndIsMain(itemsSpec.getItemId());
            newOrderItems.setItemImg(itemsImg.getUrl());
            Items items = itemService.queryItem(itemsSpec.getItemId());
            newOrderItems.setItemName(items.getItemName());
            newOrderItems.setItemSpecId(itemsSpec.getId());
            newOrderItems.setItemSpecName(itemsSpec.getName());
            newOrderItems.setPrice(itemsSpec.getPriceDiscount());
            newOrderItems.setBuyCounts(buyCounts);
            orderItemsMapper.insert(newOrderItems);

            // 在用户提交订单以后，规格表中需要扣除库存
            itemService.decreaseItemSpecStock(itemsSpec.getId(), buyCounts);
        }
        newOrder.setTotalAmount(totalAmount);
        newOrder.setRealPayAmount(realPayAmount);
        newOrder.setPostAmount(postAmount);
        newOrder.setPayMethod(payMethod);
        newOrder.setLeftMsg(leftMsg);
        newOrder.setIsComment(YesOrNo.NO.getType());
        newOrder.setIsDelete(YesOrNo.NO.getType());
        newOrder.setCreatedTime(new Date());
        newOrder.setUpdatedTime(new Date());
        ordersMapper.insert(newOrder);

        //3.插入订单状态表
        OrderStatus newOrderStatus = new OrderStatus();
        newOrderStatus.setOrderId(orderId);
        newOrderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.getType());
        newOrderStatus.setCreatedTime(new Date());
        orderStatusMapper.insert(newOrderStatus);

        //4.创建支付中心VO
        MerchantOrdersVO merchantOrdersVO = new MerchantOrdersVO();
        merchantOrdersVO.setMerchantOrderId(orderId);
        merchantOrdersVO.setMerchantUserId(userId);
        merchantOrdersVO.setPayMethod(payMethod);
        merchantOrdersVO.setAmount(realPayAmount + postAmount);

        //创建自定义VO
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(orderId);
        orderVO.setMerchantOrdersVO(merchantOrdersVO);

        return orderVO;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void notifyMerchantOrderPaid(String orderId) {
        OrderStatus updateOrderStatus = new OrderStatus();

        updateOrderStatus.setOrderId(orderId);
        updateOrderStatus.setOrderStatus(OrderStatusEnum.WAIT_DELIVER.getType());
        updateOrderStatus.setPayTime(new Date());

        orderStatusMapper.updateByPrimaryKeySelective(updateOrderStatus);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderStatus getPaidOrderInfo(String orderId) {

        OrderStatus orderStatus = orderStatusMapper.selectByPrimaryKey(orderId);

        return orderStatus;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void closePostponeOrder() {

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.getType());

        List<OrderStatus> orderStatusList = orderStatusMapper.select(orderStatus);
        for (OrderStatus o:orderStatusList){
            Date createdTime = o.getCreatedTime();
            int days = DateUtil.daysBetween(createdTime, new Date());
            if (days >= 1){
                doCloseOrder(o.getOrderId());
            }
        }

    }

    @Transactional(propagation = Propagation.REQUIRED)
    void doCloseOrder(String orderId){
        OrderStatus close = new OrderStatus();
        close.setOrderId(orderId);
        close.setOrderStatus(OrderStatusEnum.CLOSE.getType());
        close.setCloseTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(close);
    }
}
